package service

import (
	"context"
	"fmt"
	"time"

	"gitee.com/daonna/collab-manage-system/ent"
	"gitee.com/daonna/collab-manage-system/ent/activity"
	"gitee.com/daonna/collab-manage-system/ent/activityparticipant"
	"gitee.com/daonna/collab-manage-system/ent/department"
	"gitee.com/daonna/collab-manage-system/ent/user"
	"gitee.com/daonna/collab-manage-system/repository/db"
)

// --- 输入/输出结构体 (DTOs) ---

// CreateActivityInput 创建活动的输入
type CreateActivityInput struct {
	Name              string    `json:"name" binding:"required,max=100"`
	Category          string    `json:"category" binding:"required,oneof=team_building training celebration other"`
	CategoryDisplay   string    `json:"category_display" binding:"required,max=50"`
	StartTime         time.Time `json:"start_time" binding:"required"`
	EndTime           time.Time `json:"end_time" binding:"required,gtfield=StartTime"`
	Location          string    `json:"location" binding:"required,max=255"`
	Description       *string   `json:"description"` // 使用指针表示可选
	IsCompanyWide     bool      `json:"is_company_wide"`
	CreatorID         int64     `json:"creator_id" binding:"required"` // 通常从认证信息获取，但这里先显式传入
	NotificationApp   bool      `json:"notification_app"`
	NotificationEmail bool      `json:"notification_email"`
	NotificationSms   bool      `json:"notification_sms"`
	Status            string    `json:"status" binding:"omitempty,oneof=draft published"` // 创建时通常是 draft 或 published
}

// UpdateActivityInput 更新活动的输入 (字段通常是可选的)
type UpdateActivityInput struct {
	Name              *string    `json:"name" binding:"omitempty,max=100"`
	Category          *string    `json:"category" binding:"omitempty,oneof=team_building training celebration other"`
	CategoryDisplay   *string    `json:"category_display" binding:"omitempty,max=50"`
	StartTime         *time.Time `json:"start_time"`
	EndTime           *time.Time `json:"end_time"`
	Location          *string    `json:"location" binding:"omitempty,max=255"`
	Description       *string    `json:"description"`
	IsCompanyWide     *bool      `json:"is_company_wide"`
	NotificationApp   *bool      `json:"notification_app"`
	NotificationEmail *bool      `json:"notification_email"`
	NotificationSms   *bool      `json:"notification_sms"`
}

// UpdateActivityStatusInput 更新活动状态的输入
type UpdateActivityStatusInput struct {
	Status string `json:"status" binding:"required,oneof=draft published canceled completed"`
}

// ListActivitiesInput 获取活动列表的输入
type ListActivitiesInput struct {
	Page          int       `form:"page" binding:"omitempty,min=1"`
	PageSize      int       `form:"page_size" binding:"omitempty,min=1,max=100"`
	Status        string    `form:"status" binding:"omitempty,oneof=draft published canceled completed"`
	Category      string    `form:"category" binding:"omitempty,oneof=team_building training celebration other"`
	CreatorID     int64     `form:"creator_id" binding:"omitempty,min=1"`
	StartTimeFrom time.Time `form:"start_time_from" binding:"omitempty"`
	StartTimeTo   time.Time `form:"start_time_to" binding:"omitempty"`
	IsParticipant *bool     `form:"is_participant" binding:"omitempty"` // 是否只显示我参与的
}

// ActivityOutput 活动输出DTO
type ActivityOutput struct {
	ID                int64       `json:"id"`
	Name              string      `json:"name"`
	Category          string      `json:"category"`
	CategoryDisplay   string      `json:"category_display"`
	StartTime         time.Time   `json:"start_time"`
	EndTime           time.Time   `json:"end_time"`
	Location          string      `json:"location"`
	Description       *string     `json:"description"`
	IsCompanyWide     bool        `json:"is_company_wide"`
	CreatorID         int64       `json:"creator_id"`
	Creator           *UserOutput `json:"creator,omitempty"`
	NotificationApp   bool        `json:"notification_app"`
	NotificationEmail bool        `json:"notification_email"`
	NotificationSms   bool        `json:"notification_sms"`
	Status            string      `json:"status"`
	ParticipantsCount int         `json:"participants_count,omitempty"`
	IsJoined          bool        `json:"is_joined,omitempty"` // 当前用户是否已加入
	CreatedAt         time.Time   `json:"created_at"`
	UpdatedAt         time.Time   `json:"updated_at"`
}

// UserOutput 用户输出DTO (简化版)
type UserOutput struct {
	ID       int64  `json:"id"`
	Username string `json:"username"`
	Nickname string `json:"nickname,omitempty"`
	Avatar   string `json:"avatar,omitempty"`
}

// DepartmentOutput 部门输出DTO
type DepartmentOutput struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	Code string `json:"code"`
}

// ParticipantOutput 活动参与者输出DTO
type ParticipantOutput struct {
	ID           int64             `json:"id"`
	UserID       int64             `json:"user_id"`
	User         *UserOutput       `json:"user,omitempty"`
	DepartmentID int64             `json:"department_id,omitempty"`
	Department   *DepartmentOutput `json:"department,omitempty"`
	Status       string            `json:"status"`
	JoinedAt     time.Time         `json:"joined_at"`
}

// ListActivityParticipantsInput 获取活动参与者列表的输入
type ListActivityParticipantsInput struct {
	Page         int    `form:"page" binding:"omitempty,min=1"`
	PageSize     int    `form:"page_size" binding:"omitempty,min=1,max=100"`
	Status       string `form:"status" binding:"omitempty,oneof=joined left"`
	DepartmentID int64  `form:"department_id"` // 按部门过滤
}

// AddActivityParticipantsInput 批量添加活动参与者的输入
type AddActivityParticipantsInput struct {
	UserIDs      []int64 `json:"user_ids" binding:"required"`
	DepartmentID *int64  `json:"department_id"` // 可选，指定部门
}

// ActivityAttachmentInput 活动附件输入
type ActivityAttachmentInput struct {
	Name        string `form:"name" binding:"required,max=100"`
	FilePath    string `form:"file_path" binding:"required"`
	FileSize    int64  `form:"file_size" binding:"required,gt=0"`
	ContentType string `form:"content_type" binding:"required"`
}

// ActivityAttachmentOutput 活动附件输出DTO
type ActivityAttachmentOutput struct {
	ID          int64       `json:"id"`
	ActivityID  int64       `json:"activity_id"`
	Name        string      `json:"name"`
	FilePath    string      `json:"file_path"`
	FileSize    int64       `json:"file_size"`
	ContentType string      `json:"content_type"`
	CreatedAt   time.Time   `json:"created_at"`
	CreatedBy   int64       `json:"created_by"`
	Creator     *UserOutput `json:"creator,omitempty"`
}

// --- 业务功能实现 ---

// CreateActivity 创建新活动
func CreateActivity(ctx context.Context, input CreateActivityInput) (*ActivityOutput, error) {
	// 获取数据库客户端
	client := db.GetDBClient().Activity()

	// 默认状态为草稿
	status := activity.StatusDraft
	if input.Status != "" {
		status = activity.Status(input.Status)
	}

	// 检查创建者是否存在
	userClient := db.GetDBClient().User()
	exists, err := userClient.User.Query().
		Where(user.ID(input.CreatorID)).
		Exist(ctx)
	if err != nil {
		return nil, fmt.Errorf("查询创建者失败: %w", err)
	}
	if !exists {
		return nil, fmt.Errorf("创建者不存在")
	}

	// 创建活动
	a, err := client.Activity.
		Create().
		SetName(input.Name).
		SetCategory(activity.Category(input.Category)).
		SetCategoryDisplay(input.CategoryDisplay).
		SetStartTime(input.StartTime).
		SetEndTime(input.EndTime).
		SetLocation(input.Location).
		SetNillableDescription(input.Description).
		SetIsCompanyWide(input.IsCompanyWide).
		SetCreatorID(input.CreatorID).
		SetNotificationApp(input.NotificationApp).
		SetNotificationEmail(input.NotificationEmail).
		SetNotificationSms(input.NotificationSms).
		SetStatus(status).
		Save(ctx)
	if err != nil {
		return nil, fmt.Errorf("创建活动失败: %w", err)
	}

	// 重新查询以获取关联数据
	activity, err := client.Activity.
		Query().
		Where(activity.ID(a.ID)).
		WithCreator().
		Only(ctx)
	if err != nil {
		// 创建成功但查询失败，返回基本信息
		return &ActivityOutput{
			ID:                a.ID,
			Name:              a.Name,
			Category:          string(a.Category),
			CategoryDisplay:   a.CategoryDisplay,
			StartTime:         a.StartTime,
			EndTime:           a.EndTime,
			Location:          a.Location,
			Description:       &a.Description,
			IsCompanyWide:     a.IsCompanyWide,
			CreatorID:         a.CreatorID,
			NotificationApp:   a.NotificationApp,
			NotificationEmail: a.NotificationEmail,
			NotificationSms:   a.NotificationSms,
			Status:            string(a.Status),
			CreatedAt:         a.CreatedAt,
			UpdatedAt:         a.UpdatedAt,
		}, nil
	}

	return activityToOutput(activity), nil
}

// GetActivityByID 根据ID获取活动
func GetActivityByID(ctx context.Context, id int64) (*ActivityOutput, error) {
	client := db.GetDBClient().Activity()

	a, err := client.Activity.
		Query().
		Where(activity.ID(id)).
		WithCreator().
		Only(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return nil, nil // 返回 nil, nil 表示未找到
		}
		return nil, fmt.Errorf("查询活动失败: %w", err)
	}

	// 查询参与人数
	participantCount, err := db.GetDBClient().ActivityParticipant().
		ActivityParticipant.
		Query().
		Where(
			activityparticipant.ActivityID(id),
			activityparticipant.StatusEQ(activityparticipant.StatusConfirmed),
		).
		Count(ctx)
	if err != nil {
		// 忽略计数错误，继续返回活动信息
		participantCount = 0
	}

	output := activityToOutput(a)
	output.ParticipantsCount = participantCount

	return output, nil
}

// ListActivities 获取活动列表
func ListActivities(ctx context.Context, input ListActivitiesInput) ([]*ActivityOutput, int, error) {
	client := db.GetDBClient().Activity()

	// 构建查询
	query := client.Activity.Query().WithCreator()

	// 添加过滤条件
	if input.Status != "" {
		query = query.Where(activity.StatusEQ(activity.Status(input.Status)))
	}

	if input.Category != "" {
		query = query.Where(activity.CategoryEQ(activity.Category(input.Category)))
	}

	if input.CreatorID > 0 {
		query = query.Where(activity.CreatorID(input.CreatorID))
	}

	if !input.StartTimeFrom.IsZero() {
		query = query.Where(activity.StartTimeGTE(input.StartTimeFrom))
	}

	if !input.StartTimeTo.IsZero() {
		query = query.Where(activity.StartTimeLTE(input.StartTimeTo))
	}

	// 计数
	total, err := query.Clone().Count(ctx)
	if err != nil {
		return nil, 0, fmt.Errorf("统计活动总数失败: %w", err)
	}

	// 分页处理
	if input.Page <= 0 {
		input.Page = 1
	}
	if input.PageSize <= 0 {
		input.PageSize = 10
	}

	offset := (input.Page - 1) * input.PageSize

	// 查询并排序
	activities, err := query.
		Order(ent.Desc(activity.FieldCreatedAt)).
		Limit(input.PageSize).
		Offset(offset).
		All(ctx)
	if err != nil {
		return nil, 0, fmt.Errorf("查询活动列表失败: %w", err)
	}

	// 转换为输出格式
	outputs := make([]*ActivityOutput, len(activities))
	for i, a := range activities {
		outputs[i] = activityToOutput(a)

		// 查询参与人数
		participantCount, err := db.GetDBClient().ActivityParticipant().
			ActivityParticipant.
			Query().
			Where(
				activityparticipant.ActivityID(a.ID),
				activityparticipant.StatusEQ(activityparticipant.StatusConfirmed),
			).
			Count(ctx)
		if err == nil {
			outputs[i].ParticipantsCount = participantCount
		}
	}

	return outputs, total, nil
}

// UpdateActivity 更新活动信息
func UpdateActivity(ctx context.Context, id int64, input UpdateActivityInput) (*ActivityOutput, error) {
	client := db.GetDBClient().Activity()

	// 检查活动是否存在
	exists, err := client.Activity.Query().Where(activity.ID(id)).Exist(ctx)
	if err != nil {
		return nil, fmt.Errorf("查询活动失败: %w", err)
	}
	if !exists {
		return nil, nil // 返回 nil, nil 表示未找到
	}

	// 构建更新
	update := client.Activity.UpdateOneID(id)

	if input.Name != nil {
		update.SetName(*input.Name)
	}

	if input.Category != nil {
		update.SetCategory(activity.Category(*input.Category))
	}

	if input.CategoryDisplay != nil {
		update.SetCategoryDisplay(*input.CategoryDisplay)
	}

	if input.StartTime != nil {
		update.SetStartTime(*input.StartTime)
	}

	if input.EndTime != nil {
		update.SetEndTime(*input.EndTime)
	}

	if input.Location != nil {
		update.SetLocation(*input.Location)
	}

	if input.Description != nil {
		update.SetDescription(*input.Description)
	} else {
		// 如果是 nil 值但需要清空描述，可以添加对应逻辑
		// update.ClearDescription()
	}

	if input.IsCompanyWide != nil {
		update.SetIsCompanyWide(*input.IsCompanyWide)
	}

	if input.NotificationApp != nil {
		update.SetNotificationApp(*input.NotificationApp)
	}

	if input.NotificationEmail != nil {
		update.SetNotificationEmail(*input.NotificationEmail)
	}

	if input.NotificationSms != nil {
		update.SetNotificationSms(*input.NotificationSms)
	}

	// 执行更新
	updatedActivity, err := update.Save(ctx)
	if err != nil {
		return nil, fmt.Errorf("更新活动失败: %w", err)
	}

	// 重新查询完整信息
	reloadedActivity, err := client.Activity.
		Query().
		Where(activity.ID(updatedActivity.ID)).
		WithCreator().
		Only(ctx)
	if err != nil {
		// 更新成功但查询完整信息失败，返回基本信息
		return &ActivityOutput{
			ID:                updatedActivity.ID,
			Name:              updatedActivity.Name,
			Category:          string(updatedActivity.Category),
			CategoryDisplay:   updatedActivity.CategoryDisplay,
			StartTime:         updatedActivity.StartTime,
			EndTime:           updatedActivity.EndTime,
			Location:          updatedActivity.Location,
			Description:       &updatedActivity.Description,
			IsCompanyWide:     updatedActivity.IsCompanyWide,
			CreatorID:         updatedActivity.CreatorID,
			NotificationApp:   updatedActivity.NotificationApp,
			NotificationEmail: updatedActivity.NotificationEmail,
			NotificationSms:   updatedActivity.NotificationSms,
			Status:            string(updatedActivity.Status),
			CreatedAt:         updatedActivity.CreatedAt,
			UpdatedAt:         updatedActivity.UpdatedAt,
		}, nil
	}

	return activityToOutput(reloadedActivity), nil
}

// DeleteActivity 删除活动
func DeleteActivity(ctx context.Context, id int64) error {
	client := db.GetDBClient().Activity()

	// 检查是否存在
	exists, err := client.Activity.Query().Where(activity.ID(id)).Exist(ctx)
	if err != nil {
		return fmt.Errorf("查询活动失败: %w", err)
	}
	if !exists {
		return nil // 不存在时直接返回成功
	}

	// 删除活动
	err = client.Activity.DeleteOneID(id).Exec(ctx)
	if err != nil {
		return fmt.Errorf("删除活动失败: %w", err)
	}

	return nil
}

// UpdateActivityStatus 更新活动状态
func UpdateActivityStatus(ctx context.Context, id int64, input UpdateActivityStatusInput) error {
	client := db.GetDBClient().Activity()

	// 检查活动是否存在
	exists, err := client.Activity.Query().Where(activity.ID(id)).Exist(ctx)
	if err != nil {
		return fmt.Errorf("查询活动失败: %w", err)
	}
	if !exists {
		return fmt.Errorf("活动不存在")
	}

	// 更新状态
	_, err = client.Activity.
		UpdateOneID(id).
		SetStatus(activity.Status(input.Status)).
		Save(ctx)
	if err != nil {
		return fmt.Errorf("更新活动状态失败: %w", err)
	}

	return nil
}

// JoinActivity 用户加入活动
func JoinActivity(ctx context.Context, activityID, userID int64, departmentID *int64) error {
	activityClient := db.GetDBClient().Activity()
	participantClient := db.GetDBClient().ActivityParticipant()

	// 1. 检查活动是否存在
	act, err := activityClient.Activity.Get(ctx, activityID)
	if err != nil {
		if ent.IsNotFound(err) {
			return fmt.Errorf("活动不存在")
		}
		return fmt.Errorf("查询活动失败: %w", err)
	}

	// 2. 检查活动状态是否允许加入
	if act.Status != activity.StatusPublished {
		return fmt.Errorf("该活动当前状态(%s)不允许加入", act.Status)
	}

	// 3. 检查用户是否存在
	userClient := db.GetDBClient().User()
	_, err = userClient.User.Get(ctx, userID)
	if err != nil {
		if ent.IsNotFound(err) {
			return fmt.Errorf("用户不存在")
		}
		return fmt.Errorf("查询用户失败: %w", err)
	}

	// 4. 检查是否已经加入
	exists, err := participantClient.ActivityParticipant.
		Query().
		Where(
			activityparticipant.ActivityID(activityID),
			activityparticipant.UserID(userID),
			activityparticipant.StatusEQ(activityparticipant.StatusConfirmed),
		).
		Exist(ctx)
	if err != nil {
		return fmt.Errorf("检查参与记录失败: %w", err)
	}
	if exists {
		return fmt.Errorf("用户已加入该活动")
	}

	// 5. 如果指定了部门，检查部门是否存在
	if departmentID != nil {
		departmentClient := db.GetDBClient().Department()
		_, err = departmentClient.Department.Get(ctx, *departmentID)
		if err != nil {
			if ent.IsNotFound(err) {
				return fmt.Errorf("部门不存在")
			}
			return fmt.Errorf("查询部门失败: %w", err)
		}

		// 可选：检查用户是否属于该部门
		// userDeptClient := db.GetDBClient().UserDepartment()
		// isInDept, err := userDeptClient.UserDepartment.Query()...
	}

	// 6. 创建参与记录
	create := participantClient.ActivityParticipant.Create().
		SetActivityID(activityID).
		SetUserID(userID).
		SetStatus(activityparticipant.StatusConfirmed)

	// 如果有部门ID，则设置部门
	if departmentID != nil {
		create.SetDepartmentID(*departmentID)
	}

	_, err = create.Save(ctx)
	if err != nil {
		return fmt.Errorf("创建参与记录失败: %w", err)
	}

	return nil
}

// LeaveActivity 用户退出活动
func LeaveActivity(ctx context.Context, activityID, userID int64) error {
	participantClient := db.GetDBClient().ActivityParticipant()

	// 检查是否已加入
	participant, err := participantClient.ActivityParticipant.
		Query().
		Where(
			activityparticipant.ActivityID(activityID),
			activityparticipant.UserID(userID),
			activityparticipant.StatusEQ(activityparticipant.StatusConfirmed),
		).
		Only(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return fmt.Errorf("用户未加入该活动")
		}
		return fmt.Errorf("查询参与记录失败: %w", err)
	}

	// 更新状态为已退出
	_, err = participantClient.ActivityParticipant.
		UpdateOne(participant).
		SetStatus(activityparticipant.StatusDeclined).
		Save(ctx)
	if err != nil {
		return fmt.Errorf("退出活动失败: %w", err)
	}

	return nil
}

// ListActivityParticipants 获取活动参与者列表
func ListActivityParticipants(ctx context.Context, activityID int64, input ListActivityParticipantsInput) ([]*ParticipantOutput, int, error) {
	activityClient := db.GetDBClient().Activity()
	participantClient := db.GetDBClient().ActivityParticipant()

	// 1. 检查活动是否存在
	_, err := activityClient.Activity.Get(ctx, activityID)
	if err != nil {
		if ent.IsNotFound(err) {
			return nil, 0, fmt.Errorf("活动不存在")
		}
		return nil, 0, fmt.Errorf("查询活动失败: %w", err)
	}

	// 2. 构建查询
	query := participantClient.ActivityParticipant.
		Query().
		Where(activityparticipant.ActivityID(activityID)).
		WithUser().
		WithDepartment()

	// 3. 添加过滤条件
	if input.Status != "" {
		query = query.Where(activityparticipant.StatusEQ(activityparticipant.Status(input.Status)))
	} else {
		// 默认只查询已加入的用户
		query = query.Where(activityparticipant.StatusEQ(activityparticipant.StatusConfirmed))
	}

	if input.DepartmentID > 0 {
		query = query.Where(activityparticipant.DepartmentID(input.DepartmentID))
	}

	// 4. 计算总数
	total, err := query.Count(ctx)
	if err != nil {
		return nil, 0, fmt.Errorf("统计参与人数失败: %w", err)
	}

	// 5. 分页查询
	if input.Page < 1 {
		input.Page = 1
	}
	if input.PageSize < 1 {
		input.PageSize = 10
	}
	offset := (input.Page - 1) * input.PageSize

	participants, err := query.
		Limit(input.PageSize).
		Offset(offset).
		Order(ent.Desc(activityparticipant.FieldCreatedAt)).
		All(ctx)
	if err != nil {
		return nil, 0, fmt.Errorf("查询参与者失败: %w", err)
	}

	// 6. 转换为输出DTO
	outputs := make([]*ParticipantOutput, len(participants))
	for i, p := range participants {
		outputs[i] = &ParticipantOutput{
			ID:           p.ID,
			UserID:       p.UserID,
			DepartmentID: *p.DepartmentID,
			Status:       string(p.Status),
			JoinedAt:     p.CreatedAt,
		}

		// 如果预加载了用户信息，则添加到输出
		if p.Edges.User != nil {
			outputs[i].User = &UserOutput{
				ID:       p.Edges.User.ID,
				Username: p.Edges.User.Username,
				// Nickname: p.Edges.User.Nickname,
				// Avatar:   p.Edges.User.Avatar,
			}
		}

		// 如果预加载了部门信息，则添加到输出
		if p.Edges.Department != nil {
			outputs[i].Department = &DepartmentOutput{
				ID:   p.Edges.Department.ID,
				Name: p.Edges.Department.Name,
				Code: p.Edges.Department.Code,
			}
		}
	}

	return outputs, total, nil
}

// AddActivityParticipants 批量添加活动参与者
func AddActivityParticipants(ctx context.Context, activityID int64, input AddActivityParticipantsInput) error {
	activityClient := db.GetDBClient().Activity()
	participantClient := db.GetDBClient().ActivityParticipant()

	// 1. 检查活动是否存在
	act, err := activityClient.Activity.Get(ctx, activityID)
	if err != nil {
		if ent.IsNotFound(err) {
			return fmt.Errorf("活动不存在")
		}
		return fmt.Errorf("查询活动失败: %w", err)
	}

	// 2. 检查活动状态
	if act.Status != activity.StatusDraft && act.Status != activity.StatusPublished {
		return fmt.Errorf("当前活动状态不允许添加参与者")
	}

	// 3. 检查部门是否存在
	if input.DepartmentID != nil {
		departmentClient := db.GetDBClient().Department()
		exists, err := departmentClient.Department.Query().
			Where(department.ID(*input.DepartmentID)).
			Exist(ctx)
		if err != nil {
			return fmt.Errorf("查询部门失败: %w", err)
		}
		if !exists {
			return fmt.Errorf("指定的部门不存在")
		}
	}

	// 4. 批量添加参与者
	for _, userID := range input.UserIDs {
		// 检查用户是否已加入
		exists, err := participantClient.ActivityParticipant.Query().
			Where(
				activityparticipant.ActivityID(activityID),
				activityparticipant.UserID(userID),
				activityparticipant.StatusEQ(activityparticipant.StatusConfirmed),
			).
			Exist(ctx)
		if err != nil {
			return fmt.Errorf("检查用户参与状态失败: %w", err)
		}

		if exists {
			continue // 已加入的用户跳过
		}

		// 创建参与记录
		create := participantClient.ActivityParticipant.Create().
			SetActivityID(activityID).
			SetUserID(userID).
			SetStatus(activityparticipant.StatusConfirmed)

		// 如果有部门ID，则设置部门
		if input.DepartmentID != nil {
			create.SetDepartmentID(*input.DepartmentID)
		}

		_, err = create.Save(ctx)
		if err != nil {
			return fmt.Errorf("添加参与者失败 (userId=%d): %w", userID, err)
		}
	}

	return nil
}

// --- 辅助函数 ---

// activityToOutput 将活动实体转换为输出DTO
func activityToOutput(a *ent.Activity) *ActivityOutput {
	output := &ActivityOutput{
		ID:                a.ID,
		Name:              a.Name,
		Category:          string(a.Category),
		CategoryDisplay:   a.CategoryDisplay,
		StartTime:         a.StartTime,
		EndTime:           a.EndTime,
		Location:          a.Location,
		Description:       &a.Description,
		IsCompanyWide:     a.IsCompanyWide,
		CreatorID:         a.CreatorID,
		NotificationApp:   a.NotificationApp,
		NotificationEmail: a.NotificationEmail,
		NotificationSms:   a.NotificationSms,
		Status:            string(a.Status),
		CreatedAt:         a.CreatedAt,
		UpdatedAt:         a.UpdatedAt,
	}

	// 添加创建者信息
	if a.Edges.Creator != nil {
		output.Creator = &UserOutput{
			ID:       a.Edges.Creator.ID,
			Username: a.Edges.Creator.Username,
			// Nickname: a.Edges.Creator.Nickname,
			// Avatar:   a.Edges.Creator.Avatar,
		}
	}

	return output
}
